<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { onPageScroll, onReady } from '@dcloudio/uni-app'
import TnListItem from '@tuniao/tnui-vue3-uniapp/components/list/src/list-item.vue'
import TnTag from '@tuniao/tnui-vue3-uniapp/components/tag/src/tag.vue'
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import TnPicker from '@tuniao/tnui-vue3-uniapp/components/picker/src/picker.vue'
import TnRegionPicker from '@tuniao/tnui-vue3-uniapp/components/region-picker/src/region-picker.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import TnDateTimePicker from '@tuniao/tnui-vue3-uniapp/components/date-time-picker/src/date-time-picker.vue'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import { useScrollTransparentNavbar } from '@/hooks'
import {
  CHANNEL,
  FILE_URL,
  MP_API_URL,
  USER_INFO,
  USER_TOKEN,
} from '@/api/config'
import user from '@/api/user.js'

// 导航栏的高度
const navbarHeight = ref(0)
const instance = getCurrentInstance()
const {
  triggerElementId,
  navbarOpacity,
  init: initTransparentScroll,
  opacityScrollHandle,
} = useScrollTransparentNavbar(instance)
const state = reactive({
  loading: false,
  showNicknamePopup: false,
  showIdNumberPopup: false,
  showSexPicker: false,
  sexPickerData: [
    { label: '男', value: 1 },
    { label: '女', value: 2 },
    { label: '保密', value: 0 },
  ],
  showBirthdayPicker: false,
  showIntroducePopup: false,
  openHometownPicker: false,
  showProfessionPicker: false,
  showSchoolPopup: false,
  userToken: '',
  userInfo: {
    username: '',
    nickname: '',
    introduce: '',
    avatar: '',
    personal_bg: '',
    birthday: '',
    age: '',
    gender: '',
    gender_text: '',
    hometown: '',
    entrance_year: '',
    school: '',
    occupation: '',
    labels: [],
    label_ids: '',
    ip_territory: '未知',
    id_number: '',
    register_date: '',
    circles_total: 0,
    fans_total: 0,
    follow_total: 0,
    dynamic_total: 0,
  },
  channel: '',
  professionPickerData: [
    '农林牧渔业',
    '采矿业',
    '生产制造',
    '服务业',
    '普工/技工',
    '交通运输',
    '批发零售',
    '住宿餐饮',
    '运营/客服',
    '房地产建筑',
    '教育培训',
    '金融/贸易',
    '互联网/通信',
    '医疗/健康',
    '人事/行政/财务',
    '安保消防',
    '传媒/影视',
    '美容/美发',
    '设计',
    '市场',
    '咨询/翻译/法律',
  ],
})

const saveUserInfo = (data: object, type = '') => {
  state.loading = true
  user
    .updateUserInfo(data)
    .then((res) => {
      uni.showToast({
        title: res.msg,
        icon: 'none',
      })
      if (res.code == 1) {
        state.loading = false
        if (type != 'file') {
          uni.setStorageSync(USER_INFO, res.data.userInfo)
          state.userInfo = res.data.userInfo
        }
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

const chooseAvatarFile = () => {
  uni.chooseImage({
    count: 1,
    success(res) {
      if (res.errMsg == 'chooseImage:ok') {
        const tempFilePaths = res.tempFilePaths
        uni.uploadFile({
          url: `${MP_API_URL}/system.System/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            Authorization: uni.getStorageSync(USER_TOKEN),
          },
          formData: {
            typeEnum: 'IMAGE',
          },
          success(uploadFileRes) {
            const result = JSON.parse(uploadFileRes.data)
            if (result.code == 1) {
              // state.userInfo.avatar = result.data.file.url
              // const userInfo = uni.getStorageSync(USER_INFO) || {}
              // userInfo.avatar = result.data.file.url
              // uni.setStorageSync(USER_INFO, userInfo)
              saveUserInfo(
                {
                  avatar: result.data.file.url,
                  channel: state.channel,
                },
                'file'
              )
            }
          },
          fail(uploadFileErr) {
            console.log(uploadFileErr)
            uni.showToast({
              title: uploadFileErr,
              icon: 'none',
            })
          },
        })
      }
    },
  })
}
const choosePersonalBgFile = () => {
  uni.chooseImage({
    count: 1,
    success(res) {
      if (res.errMsg == 'chooseImage:ok') {
        const tempFilePaths = res.tempFilePaths
        uni.uploadFile({
          url: `${MP_API_URL}/system.System/upload`,
          filePath: tempFilePaths[0],
          name: 'file',
          header: {
            Authorization: uni.getStorageSync(USER_TOKEN),
          },
          formData: {
            typeEnum: 'IMAGE',
          },
          success(uploadFileRes) {
            const result = JSON.parse(uploadFileRes.data)
            if (result.code == 1) {
              // state.userInfo.personal_bg = result.data.file.url
              // const userInfo = uni.getStorageSync(USER_INFO) || {}
              // userInfo.personal_bg = result.data.file.url
              // uni.setStorageSync(USER_INFO, userInfo)
              saveUserInfo(
                {
                  personal_bg: result.data.file.url,
                  channel: state.channel,
                },
                'file'
              )
            }
          },
          fail(uploadFileErr) {
            console.log(uploadFileErr)
            uni.showToast({
              title: uploadFileErr,
              icon: 'none',
            })
          },
        })
      }
    },
  })
}

// 用户昵称
const clickNickname = () => {
  state.showNicknamePopup = true
}
// 保存用户昵称
const confirmNickname = () => {
  if (state.userInfo.nickname == '') {
    uni.showToast({
      title: '请填写昵称',
      icon: 'none',
    })
    return
  }

  saveUserInfo({
    nickname: state.userInfo.nickname,
    channel: state.channel,
  })
  state.showNicknamePopup = false
}

// 用户ID号
const clickIdNumber = () => {
  if (state.userInfo.is_vip == 0) {
    uni.showToast({
      title: '非会员无法修改ID号！',
      icon: 'none',
    })
    return
  }
  state.showIdNumberPopup = true
}

const confirmIdNumber = () => {
  if (state.userInfo.id_number == '') {
    uni.showToast({
      title: '请填写ID号',
      icon: 'none',
    })
    return
  }
  saveUserInfo({
    id_number: state.userInfo.id_number,
  })
  state.showIdNumberPopup = false
}

// 用户性别
const openSexPicker = () => {
  state.showSexPicker = true
}
const confirmGender = (value: any, item: any) => {
  // item.label 男
  // item.value 1
  saveUserInfo({
    gender: item.value,
  })
  state.showSexPicker = false
}
const UserSex: {
  [key: number]: string
} = {
  0: '保密',
  1: '男',
  2: '女',
}

// 生日选择
const openBirthdayPicker = () => {
  state.showBirthdayPicker = true
}
const confirmBirthday = (value: string) => {
  // value 1995-06-07
  console.log(value, 'confirmBirthday')
  saveUserInfo({
    birthday: value,
  })
  state.showBirthdayPicker = false
}

// 用户简介
const clickIntroduce = () => {
  state.showIntroducePopup = true
}
// 保存用户简介
const confirmIntroduce = () => {
  if (state.userInfo.introduce == '') {
    uni.showToast({
      title: '请填写简介',
      icon: 'none',
    })
    return
  }
  saveUserInfo({
    introduce: state.userInfo.introduce,
    channel: state.channel,
  })
  state.showIntroducePopup = false
}

// 家乡
const clickHometown = () => {
  state.openHometownPicker = true
}
const confirmHometown = (value: string[], item: any) => {
  state.userInfo.hometown = `${item[0].name}/${item[1].name}/${item[2].name}`
  saveUserInfo({
    hometown: state.userInfo.hometown,
  })
  state.openHometownPicker = false
}

// 行业
const openProfessionPicker = () => {
  state.showProfessionPicker = true
}
const confirmOccupation = (value: any) => {
  state.userInfo.occupation = value
  saveUserInfo({
    occupation: state.userInfo.occupation,
  })
  state.showProfessionPicker = false
}

// 学校
const clickSchool = () => {
  state.showSchoolPopup = true
}
// 保存学校信息
const confirmSchool = () => {
  if (state.userInfo.school == '') {
    uni.showToast({
      title: '请填写学校',
      icon: 'none',
    })
    return
  }
  if (state.userInfo.entrance_year == '') {
    uni.showToast({
      title: '请填写入学年份',
      icon: 'none',
    })
    return
  }
  saveUserInfo({
    school: state.userInfo.school,
    entrance_year: state.userInfo.entrance_year,
    channel: state.channel,
  })
  state.showSchoolPopup = false
}

// 显示修改用户信息弹框
// const showUpdateUserInfoPopup = ref<boolean>(false)
// const openUpdateUserInfoPopup = () => {
//   showUpdateUserInfoPopup.value = true
// }

// 导航栏初始化完毕
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  navbarHeight.value = info.height
}
onMounted(() => {
  const userInfo = uni.getStorageSync(USER_INFO)
  if (userInfo) {
    state.userInfo = userInfo
  }
  const userToken = uni.getStorageSync(USER_TOKEN)
  if (userToken) {
    state.userToken = userToken
  }

  state.channel = uni.getStorageSync(CHANNEL)
})
onReady(() => {
  initTransparentScroll()
})
onPageScroll((e) => {
  opacityScrollHandle(e.scrollTop)
})
</script>

<template>
  <TnNavbar
    fixed
    :bg-color="`rgba(255, 255, 255, ${navbarOpacity})`"
    :bottom-shadow="false"
    :placeholder="false"
    @init-finish="navbarInitFinishHandle"
  />

  <view
    class="user-info"
    :style="
      'background: url(' +
      FILE_URL +
      state.userInfo.personal_bg +
      '); background-repeat: no-repeat;background-size: cover;background-position: center center;'
    "
  >
    <view class="content">
      <view class="info">
        <TnButton
          bg-color="#78909c"
          height="60"
          shape="round"
          :custom-style="{
            padding: '0 22rpx',
            color: '#ffffff',
          }"
          @click="choosePersonalBgFile"
        >
          <TnIcon name="camera" size="35" class="tn-mr-xs" /> 更换背景
        </TnButton>
      </view>
    </view>
  </view>

  <view :id="triggerElementId" class="info-list">
    <view class="avatar">
      <image
        style="width: 100%; height: 210rpx"
        :src="FILE_URL + state.userInfo.avatar"
        mode="aspectFill"
        @click="chooseAvatarFile"
      />
    </view>
    <view class="list-container">
      <view class="list-item">
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="clickNickname">
            <view class="text tn-flex">昵称</view>
            <view class="tn-text-xs sub-text">
              {{ state.userInfo.nickname || '填写昵称' }}
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="clickIdNumber">
            <view class="text tn-flex">ID号</view>
            <view class="tn-text-xs sub-text">
              {{ state.userInfo.id_number }}
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="openSexPicker">
            <view class="text">性别</view>
            <view class="tn-text-xs sub-text">
              {{ UserSex?.[state.userInfo.gender] || '请选择性别' }}
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="openBirthdayPicker">
            <view class="text">生日</view>
            <view class="tn-text-xs sub-text">
              {{ state.userInfo.birthday || '请选择生日' }}
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view
            class="list-content"
            @tap.stop="
              tnNavPage(
                '/minePages/labels?labelIds=' + state.userInfo.label_ids
              )
            "
          >
            <view class="text">标签</view>
            <view class="tn-text-xs sub-text tn-text-ellipsis-2">
              <TnTag
                v-for="(item, index) in state.userInfo.labels"
                :key="index"
                shape="round"
                bg-color="tn-gradient-bg__grey-light"
                text-color="#838383"
                :custom-style="{
                  borderRadius: '50rpx',
                  marginBottom: '2rpx',
                  fontSize: '26rpx',
                  marginRight: '5rpx',
                }"
                @click="
                  tnNavPage(
                    '/minePages/labels?labelIds=' + state.userInfo.label_ids
                  )
                "
              >
                {{ item }}
              </TnTag>
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="clickIntroduce">
            <view class="text">简介</view>
            <view class="tn-text-xs sub-text tn-text-ellipsis-1">
              {{ state.userInfo.introduce || '填写简介' }}
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="clickHometown">
            <view class="text">家乡</view>
            <view class="tn-text-xs sub-text tn-text-ellipsis-1">
              {{ state.userInfo.hometown || '填写家乡，发现老乡' }}
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="openProfessionPicker">
            <view class="text">行业</view>
            <view class="tn-text-xs sub-text tn-text-ellipsis-1">
              {{ state.userInfo.occupation || '填写行业，发现同行' }}
            </view>
          </view>
        </TnListItem>
        <TnListItem bottom-border bottom-border-indent right-icon="right">
          <view class="list-content" @tap.stop="clickSchool">
            <view class="text">学校</view>
            <view class="tn-text-xs sub-text tn-text-ellipsis-2">
              {{ state.userInfo.school || '填写学校，发现校友' }}
              {{ state.userInfo.entrance_year }}<span v-if="state.userInfo.entrance_year != ''">级</span>
            </view>
          </view>
        </TnListItem>
      </view>
    </view>
  </view>
  <!-- 填写昵称 -->
  <TnPopup
    v-model="state.showNicknamePopup"
    :close-btn="true"
    width="80%"
    height="300"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 填写昵称 </view>
    <view class="tn-pl tn-pr">
      <TnInput
        v-model="state.userInfo.nickname"
        :underline="true"
        :maxlength="20"
        placeholder="请输入用户昵称"
      />
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmNickname">
        保存
      </TnButton>
    </view>
  </TnPopup>

  <!-- 填写ID号 -->
  <TnPopup
    v-model="state.showIdNumberPopup"
    :close-btn="true"
    width="80%"
    height="300"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 填写ID号 </view>
    <view class="tn-pl tn-pr">
      <TnInput
        v-model="state.userInfo.id_number"
        type="number"
        :underline="true"
        :maxlength="10"
        placeholder="请输入ID号"
      />
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmIdNumber">
        保存
      </TnButton>
    </view>
  </TnPopup>

  <!-- 填写简介 -->
  <TnPopup
    v-model="state.showIntroducePopup"
    :close-btn="true"
    width="80%"
    height="410"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 填写简介 </view>
    <view class="tn-pl tn-pr">
      <TnInput
        v-model="state.userInfo.introduce"
        type="textarea"
        :underline="true"
        :maxlength="255"
        height="190"
        placeholder="请输入简介、介绍"
      />
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmIntroduce">
        保存
      </TnButton>
    </view>
  </TnPopup>

  <!-- 填写学校 -->
  <TnPopup
    v-model="state.showSchoolPopup"
    :close-btn="true"
    width="80%"
    height="400"
  >
    <view class="tn-p tn-text-center tn-text-lg"> 填写学校 </view>
    <view class="tn-pl tn-pr">
      <TnInput
        v-model="state.userInfo.school"
        :underline="true"
        :maxlength="20"
        placeholder="学校名称"
      />
    </view>
    <view class="tn-pl tn-pr tn-mt">
      <TnInput
        v-model="state.userInfo.entrance_year"
        type="number"
        :underline="true"
        :maxlength="4"
        placeholder="入学年份（2010）"
      >
        <template #suffix> 级 </template>
      </TnInput>
    </view>
    <view class="tn-pt">
      <TnButton text width="100%" size="lg" @click="confirmSchool">
        保存
      </TnButton>
    </view>
  </TnPopup>

  <!-- 选择家乡 -->
  <TnRegionPicker
    v-model:open="state.openHometownPicker"
    @confirm="confirmHometown"
  />

  <!-- 性别选择 -->
  <TnPicker
    v-model:open="state.showSexPicker"
    v-model="state.userInfo.gender"
    :data="state.sexPickerData"
    @confirm="confirmGender"
  />
  <!-- 生日选择 -->
  <TnDateTimePicker
    v-model:open="state.showBirthdayPicker"
    v-model="state.userInfo.birthday"
    type="date"
    format="YYYY-MM-DD"
    min-time="1949-01-01"
    @confirm="confirmBirthday"
  />
  <!-- 职业选择 -->
  <TnPicker
    v-model:open="state.showProfessionPicker"
    v-model="state.userInfo.occupation"
    :data="state.professionPickerData"
    @confirm="confirmOccupation"
  />
</template>

<style lang="scss" scoped>
@use './styles/userinfo.scss';
</style>
